﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

public class Student
{
    public string StudentId { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Major { get; set; }

    public Student(string studentId, string name, int age, string major)
    {
        StudentId = studentId;
        Name = name;
        Age = age;
        Major = major;
    }

    public override string ToString()
    {
        return $"学号: {StudentId}, 姓名: {Name}, 年龄: {Age}, 专业: {Major}";
    }
}

public class JsonFileManager
{
    public static void SerializeToFile(List<Student> students, string filePath)
    {
        try
        {
            string jsonString = JsonSerializer.Serialize(students, new JsonSerializerOptions
            {
                WriteIndented = true
            });
            File.WriteAllText(filePath, jsonString);
            Console.WriteLine($"成功序列化 {students.Count} 个学生到文件: {filePath}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"序列化失败: {ex.Message}");
        }
    }

    public static List<Student> DeserializeFromFile(string filePath)
    {
        try
        {
            if (!File.Exists(filePath))
            {
                Console.WriteLine("文件不存在");
                return new List<Student>();
            }

            string jsonString = File.ReadAllText(filePath);
            List<Student> students = JsonSerializer.Deserialize<List<Student>>(jsonString);
            Console.WriteLine($"成功从文件反序列化 {students.Count} 个学生");
            return students;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"反序列化失败: {ex.Message}");
            return new List<Student>();
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<Student> students = new List<Student>
        {
            new Student("2024001", "张三", 20, "计算机科学"),
            new Student("2024002", "李四", 19, "软件工程"),
            new Student("2024003", "王五", 21, "网络安全")
        };

        string filePath = "students.json";

        JsonFileManager.SerializeToFile(students, filePath);
        List<Student> loadedStudents = JsonFileManager.DeserializeFromFile(filePath);

        Console.WriteLine("\n=== 反序列化的学生信息 ===");
        foreach (var student in loadedStudents)
        {
            Console.WriteLine(student);
        }
    }
}